// pages/planListAdmin/index.ts

import { fontSizeCalc, handleCode, handleErrCode } from "../../utils/util";
import { adoptSubmit, getCuesSubmitPage } from "../../service/api/api-cues-submit";

const rules = [{
  name: "reward",
  rule: ["required", "isAmount", "range:[0.01,100]"],
  msg: ["积分不能为空", "请输入数字，保留两位小数", "范围0.01-100"]
}]

let toast;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0,// 选题计划id
    planId: 0,// 选题计划id
    run: 0,// 状态
    subPlan: {},// 计划详情
    access: {} as any,// 当前用户权限
    currentUser: {},// 当前用户信息
    options: '',
    isAdmin: false,// 是否是管理员查看详情
    imgUrl: [],// 图片Url
    reportList: [],// 子任务的提交的上报列表
    galleryShow: false,// 是否显示图片预览
    name: '',
    describes: '',
    searchLock: false,// 请求锁
    clickLock: false,// 点击的锁

    modal: false,// 是否显示弹窗
    showAdd: false,// 是否显示添加
    modalReward: '',// 弹窗输入的积分
    curReport: {},// 当前编辑的纪录

    scrollTop: 0, // 滚动到顶部
    triggered: false,// 自定义下拉是否被触发 true 表示下拉刷新已经被触发，false 表示下拉刷新未被触发
    searchTimeout: null,

    current: 1,// 第几页
    pageSize: 20,// 每页多少条数据
    total: 0,// 总共有多少条

    labelSize: fontSizeCalc(32),
    inputSize: fontSizeCalc(32),
    btnHeight: fontSizeCalc(96) + 'rpx',
    btnLineHeight: fontSizeCalc(70) + 'rpx',
    opLabelSize: fontSizeCalc(24),
    opBtnWidth: fontSizeCalc(140) + 'rpx',
    opBtnHeight: fontSizeCalc(50) + 'rpx',
    opBtnLineHeight: fontSizeCalc(20) + 'rpx',
    fabWidth: fontSizeCalc(108),
    fabHeight: fontSizeCalc(108),
    fabRight: fontSizeCalc(80),
    fabBottom: fontSizeCalc(100),

    title: {
      text: '',
      size: 30,
      color: '#1890FF',
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const { id, planId, name, describes, isAdmin, run } = options;
    const { globalData: { access, currentUser } } = getApp();
    this.setData({
      access,
      name,
      ['title.text']: name,
      describes,
      id,
      planId,
      run,
      isAdmin: isAdmin === 'true',
      showAdd: access.线索上报x选题计划x选题列表x上报线索 &&
        run == 1,
      currentUser,
      options: JSON.stringify(options)
    })
    this.getSubReportList({ id, planId });
  },

  /**
   * 处理一下上报的状态
   * @param data
   */
  handleReportType({ isAdopt }) {
    return {
      typeName: isAdopt === 1 ? '已录用' : '未录用',
      bgColor: isAdopt === 1 ? '#389E0D' : '#F5A34D',
    }
  },

  /**
   * 通过id获取子任务列表
   * @param id
   * @param planId
   * @param current
   */
  async getSubReportList({ id, planId, current = 1 }) {
    let _that = this;
    if (_that.data.searchLock) {
      return
    }
    let { pageSize } = this.data;
    // if (_that.isEnd()){
    //     return
    // }
    _that.setData({
      searchLock: true,
      current
    })
    wx.showLoading({
      title: '查询中...'
    })
    // 执行搜索函数
    await getCuesSubmitPage({
      current,
      pageSize,
      topicId: id,
      topicPlanId: planId,
    }).then(async (res) => {
      let dataList = [], total = _that.data.total;
      let list = res.data?.data || [];
      dataList = list.map(item => {
        const { typeName, bgColor } = this.handleReportType(item);
        item.bgColor = bgColor;
        item.typeName = typeName;
        return item
      }) || [];
      total = res.data?.total || 0;

      const oldList = this.data.reportList
      if (this.data.current > 1) {// 上拉加载更多
        dataList = [...oldList, ...dataList]
      }
      _that.setData({
        reportList: dataList,
        total
      })
    }).catch(error => {
      console.warn(error)
      handleErrCode()
    }).finally(() => {
      _that.searchFinally()
      _that.setData({
        searchLock: false
      })
    })
  },

  /**
   * 录用与不录用
   */
  async adoptSubmitFun(params) {
    let _that = this;
    if (!_that.data.isAdmin) {
      return
    }
    const { isSelfAdopt } = this.data.curReport;
    const { id, planId } = this.data;
    const tips = isSelfAdopt === 1 ? '取消录用' : '录用';
    wx.showLoading({
      title: tips + '中...'
    })
    // 执行搜索函数
    await adoptSubmit(params).then(async (response) => {
      handleCode(response, tips + '成功');
      setTimeout(() => {
        _that.getSubReportList({ id, planId });
      }, 1000)
    }).catch(error => {
      console.warn(error)
      handleErrCode()
    }).finally(() => {
      wx.hideLoading();
      _that.modalCancel();
    })
  },

  /**
   * 上报详情点击
   */
  subReportClick(e: any) {
    const report = e.currentTarget.dataset.item || {};
    wx.navigateTo({
      url: `/pages/planDetailAdmin/index?id=${report.id}&&isAdmin=${this.data.isAdmin}`,
    })
  },

  /**
   * 添加界面
   */
  addReport() {
    if (this.data.clickLock) {
      return
    }
    this.setData({
      clickLock: true
    })
    const { id, planId } = this.data;
    let _that = this;
    wx.navigateTo({
      url: `/pages/cuesAdd/index?topicId=${id}&&topicPlanId=${planId}`,
      success: function (res) {
        _that.setData({
          clickLock: false
        })
      }
    })
  },

  /**
   * 显示弹窗弹窗
   */
  showModal(e: any) {
    const report = e.currentTarget.dataset.item || {};
    this.setData({
      modal: true,
      curReport: report,
      modalReward: report.reward ?? (report.isAdopt === 1 ? 0 : ''),
    })
  },

  /**
   * 关闭弹窗弹窗
   */
  modalCancel() {
    this.setData({
      modal: false,
      modalReward: '',
    })
  },

  /**
   * 收录确认弹窗
   */
  modalConfirmFun() {
    const { curReport, modalReward } = this.data || {}
    let formData = {
      reward: modalReward
    };
    this.selectComponent("#form").validate(formData, rules).then(res => {
      this.adoptSubmitFun({ ...formData, id: curReport.id || 0 })
    }).catch(errors => {
      console.log(errors)
    })
  },

  /**
   * 收录确认弹窗
   */
  confirmFun(e: any) {
    const report = e.currentTarget.dataset.item || {};
    this.adoptSubmitFun({ id: report.id || 0 })
  },

  /**
   * 提示语
   */
  showToast(title) {
    let params = {
      title,
    }
    toast && toast.show(params);
  },

  /**
   * 是否到底的判断
   */
  isEnd() {
    let { current, pageSize, total } = this.data;
    if (total && current !== 1 && current * pageSize >= total) {
      this.showToast('已经到底了')
      return true
    } else {
      return false
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    toast = this.selectComponent("#toast")
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const { id, planId } = this.data;
    this.getSubReportList({ id, planId });
    wx.hideShareMenu({
      menus: ['shareAppMessage', 'shareTimeline'],// 隐藏分享到朋友和分享到朋友圈
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
  },

  /**
   * scroll-view 下拉刷新
   */
  refresherPulling() {
    this.setData({
      triggered: true
    })
  },

  /**
   * 刷新函数
   */
  refreshFun(e: object, current = 1) {
    // 标题栏显示刷新图标，转圈圈
    wx.showNavigationBarLoading()
    const { id, planId } = this.data;

    this.getSubReportList({ id, planId ,current });
    clearTimeout(this.data.searchTimeout);
    let searchTimeout = setTimeout(() => {
      this.searchFinally()
    }, 2000);
    this.setData({
      searchTimeout,
    })
  },

  /**
   * 下拉加载更多数据函数
   */
  scrollToLowerFun() {
    if (this.isEnd()) {
      return
    }
    // 调用刷新函数
    this.refreshFun({}, this.data.current + 1)
  },

  /**
   * 搜索最终
   */
  searchFinally() {
    clearTimeout(this.data.searchTimeout)
    // 标题栏隐藏刷新转圈圈图标
    wx.hideNavigationBarLoading();
    wx.stopPullDownRefresh();
    wx.hideLoading();
    this.setData({
      triggered: false
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  taskExecuteShareFun() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
  }
})